# 基础配置
CXX = g++
CXXFLAGS = -std=c++17 -Wall -Wextra -fPIC -O2
INCLUDES = -I./include
LDFLAGS = -shared

# 依赖配置
PKG_CONFIG ?= pkg-config
ifeq ($(shell $(PKG_CONFIG) --exists spdlog nlohmann_json && echo 0),0)
    INCLUDES += $(shell $(PKG_CONFIG) --cflags spdlog nlohmann_json)
    LIBS = $(shell $(PKG_CONFIG) --libs spdlog nlohmann_json) -lseccomp
else
    $(error Required dependencies not found: spdlog nlohmann_json)
endif

SRC_DIR = src
SOURCES = $(SRC_DIR)/cgroup_manager.cpp $(SRC_DIR)/namespace_manager.cpp $(SRC_DIR)/sandbox.cpp $(SRC_DIR)/sandbox_manager.cpp $(SRC_DIR)/seccomp_filter.cpp
OBJECTS = $(SOURCES:.cpp=.o)
TARGET = libjudge.so

TEST_DIR = tests
TEST_SOURCES = $(wildcard $(TEST_DIR)/*.cpp)
TEST_OBJECTS = $(TEST_SOURCES:.cpp=.o)
TEST_TARGET = test_judge
TEST_LIBS = -lgtest -lgtest_main -pthread

.PHONY: all clean test install run examples docker-build docker-run docker-test

# 默认目标: 构建库和示例
all: $(TARGET) examples

$(TARGET): $(OBJECTS)
	$(CXX) $(LDFLAGS) -o $@ $^ $(LIBS)

%.o: %.cpp
	$(CXX) $(CXXFLAGS) $(INCLUDES) -c $< -o $@

test: $(TARGET) $(TEST_OBJECTS)
	$(CXX) -o $(TEST_TARGET) $(TEST_OBJECTS) -L. -ljudge $(TEST_LIBS)
	./$(TEST_TARGET)

install: $(TARGET)
	install -d $(DESTDIR)/usr/local/lib
	install -m 755 $(TARGET) $(DESTDIR)/usr/local/lib
	install -d $(DESTDIR)/usr/local/include/judge
	install -m 644 include/*.h $(DESTDIR)/usr/local/include/judge

clean:
	rm -f $(OBJECTS) $(TEST_OBJECTS) $(TEST_TARGET)
# -lnlohmann_json
# 运行主程序 (使用已构建的库)
run: $(TARGET)
	$(CXX) $(CXXFLAGS) $(INCLUDES) main.cpp -o main -L. -ljudge $(LIBS)
	./main

# 构建示例程序
examples:
	@$(MAKE) -s -C examples

# Docker 目标
docker-build:
	docker build --no-cache -t judge-sandbox .

docker-run:
	docker run -it --rm --privileged judge-sandbox

docker-test:
	docker run -it --rm --privileged judge-sandbox /judge/build/test_judge